package com.example.ftp;

import org.apache.ftpserver.FtpServer;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

import static com.example.ftp.DebugLog.LOG;

/**
 * Created Date 2019/4/16
 *
 * @author liangkun
 * description：FTp服务器
 */
public class FtpServerUtil {
    private FtpServer mFtpServer;
    private String hostip;

    /**
     * 开启FTP服务器
     *
     * @param hostip 本机ip
     */
    public void startFtpServer(final String hostip) {
        new Thread(new Runnable() {
            @Override
            public void run() {
//                if (!new File(filename).exists()){
//                    creatDirsFiles();
//                }
//                creatDirsFiles();
//                FtpServerFactory serverFactory = new FtpServerFactory();
//                PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
//                File files = new File(filename);
//                //设置配置文件
//                userManagerFactory.setFile(files);
//                serverFactory.setUserManager(userManagerFactory.createUserManager());
//
//                // 设置监听IP和端口号
//                ListenerFactory factory = new ListenerFactory();
//                factory.setPort(PORT);
//                factory.setServerAddress(hostip);
//                serverFactory.addListener("default", factory.createListener());
//                BaseUser user = new BaseUser();
//
//                //设置权限
//                List<Authority> authorities = new ArrayList<Authority>();
//                authorities.add(new WritePermission());
//                user.setAuthorities(authorities);
//                //设置用户名密码
//                user.setName("admin");
//                user.setPassword("123456");
//                user.setEnabled(true);
//                user.setMaxIdleTime(3000);
//                user.setHomeDirectory(dirname);
//                try {
//                    serverFactory.getUserManager().save(user);
//                } catch (FtpException e) {
//                    e.printStackTrace();
//                }
                if (mFtpServer != null) {
                    mFtpServer.stop();
                }
                // start the server
////                mFtpServer = serverFactory.createServer();
//                try {
//                    mFtpServer.start();
////                    FTPClientUtils.getIntance().ftpConnet();
//                    DebugLog.d(LOG+"开启了FTP服务器  ip = " + hostip);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }
        }).start();
    }

    /**
     * 关闭FTP服务器
     */
    public void stopFtpServer() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (mFtpServer != null) {
                    mFtpServer.stop();
                    mFtpServer = null;
                    DebugLog.d(LOG + "关闭了FTP服务器 ip = " + hostip);
                }
            }
        }).start();
    }

    /**
     * 获取本机ip
     */
    public String getLocalIpAddress() {
        try {
            List<NetworkInterface> interfaces = Collections
                    .list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf
                        .getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress().toUpperCase();
                        boolean isIPv4 = Isipv4(sAddr);
                        if (isIPv4) {
                            return sAddr;
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    public void onStartServer() {
        hostip = getLocalIpAddress();
        DebugLog.d(LOG+"获取本机IP = " + hostip);
        startFtpServer(hostip);

    }

    public static boolean Isipv4(String ipv4) {
        if (ipv4 == null || ipv4.length() == 0) {
            return false;//字符串为空或者空串
        }
        //因为java doc里已经说明, split的参数是reg, 即正则表达式, 如果用"|"分割, 则需使用"\\|"
        String[] parts = ipv4.split("\\.");
        if (parts.length != 4) {//分割开的数组根本就不是4个数字
            return false;
        }
        for (int i = 0; i < parts.length; i++) {
            try {
                int n = Integer.parseInt(parts[i]);
                //数字不在正确范围内
                if (n < 0 || n > 255) {
                    return false;
                }
            } catch (NumberFormatException e) {//转换数字不正确
                return false;
            }
        }
        return true;
    }


}
